'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

interface Customer {
  id: number;
  name: string;
  email: string;
}

interface Product {
  id: number;
  name: string;
  price: number;
  sku: string;
}

interface OrderItem {
  productId: number;
  quantity: number;
  price: number;
  subtotal: number;
}

export default function AddOrderPage() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [selectedCustomer, setSelectedCustomer] = useState<number | ''>('');
  const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const router = useRouter();

  useEffect(() => {
    fetchCustomers();
    fetchProducts();
  }, []);

  const fetchCustomers = async () => {
    try {
      const response = await fetch('/api/customers');
      if (!response.ok) throw new Error('获取客户列表失败');
      const data = await response.json();
      setCustomers(data);
    } catch (error) {
      console.error('获取客户失败:', error);
      setError('获取客户列表失败');
    }
  };

  const fetchProducts = async () => {
    try {
      const response = await fetch('/api/products');
      if (!response.ok) throw new Error('获取产品列表失败');
      const data = await response.json();
      setProducts(data);
    } catch (error) {
      console.error('获取产品失败:', error);
      setError('获取产品列表失败');
    }
  };

  const addOrderItem = () => {
    setOrderItems([...orderItems, { productId: 0, quantity: 1, price: 0, subtotal: 0 }]);
  };

  const updateOrderItem = (index: number, field: keyof OrderItem, value: any) => {
    const newItems = [...orderItems];
    const product = products.find(p => p.id === (field === 'productId' ? Number(value) : newItems[index].productId));
    
    if (field === 'productId') {
      newItems[index].productId = Number(value);
      newItems[index].price = product?.price || 0;
    } else if (field === 'quantity') {
      newItems[index].quantity = Number(value);
    }
    
    newItems[index].subtotal = newItems[index].price * newItems[index].quantity;
    setOrderItems(newItems);
  };

  const removeOrderItem = (index: number) => {
    setOrderItems(orderItems.filter((_, i) => i !== index));
  };

  const calculateTotal = () => {
    return orderItems.reduce((total, item) => total + item.subtotal, 0);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedCustomer || orderItems.length === 0) {
      setError('请选择客户并添加至少一个商品');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/orders', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          customerId: selectedCustomer,
          totalAmount: calculateTotal(),
          status: 'pending',
          items: orderItems
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '创建订单失败');
      }

      router.push('/orders');
      router.refresh();
      
    } catch (error: any) {
      console.error('创建订单失败:', error);
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/orders" className="text-gray-600 hover:text-gray-900">
            ← 返回订单列表
          </Link>
          <h1 className="text-3xl font-bold">新建订单</h1>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">
          {error}
        </div>
      )}

      <div className="bg-white rounded-lg shadow p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 客户选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              选择客户 *
            </label>
            <select
              value={selectedCustomer}
              onChange={(e) => setSelectedCustomer(Number(e.target.value))}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            >
              <option value="">请选择客户</option>
              {customers.map((customer) => (
                <option key={customer.id} value={customer.id}>
                  {customer.name} - {customer.email}
                </option>
              ))}
            </select>
          </div>

          {/* 订单商品 */}
          <div>
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-semibold">订单商品</h3>
              <button
                type="button"
                onClick={addOrderItem}
                className="px-3 py-1 bg-green-600 text-white text-sm rounded-md hover:bg-green-700"
              >
                + 添加商品
              </button>
            </div>

            {orderItems.length === 0 ? (
              <div className="text-center text-gray-500 py-8 border-2 border-dashed border-gray-300 rounded-md">
                请添加至少一个商品
              </div>
            ) : (
              <div className="space-y-4">
                {orderItems.map((item, index) => (
                  <div key={index} className="p-4 border border-gray-200 rounded-md bg-gray-50">
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                          商品
                        </label>
                        <select
                          value={item.productId}
                          onChange={(e) => updateOrderItem(index, 'productId', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                          required
                        >
                          <option value="0">选择商品</option>
                          {products.map((product) => (
                            <option key={product.id} value={product.id}>
                              {product.name} - ¥{product.price}
                            </option>
                          ))}
                        </select>
                      </div>

                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                          数量
                        </label>
                        <input
                          type="number"
                          min="1"
                          value={item.quantity}
                          onChange={(e) => updateOrderItem(index, 'quantity', e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                          required
                        />
                      </div>

                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                          单价
                        </label>
                        <input
                          type="number"
                          value={item.price}
                          readOnly
                          className="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-100"
                        />
                      </div>

                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                          小计
                        </label>
                        <input
                          type="number"
                          value={item.subtotal}
                          readOnly
                          className="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-100"
                        />
                      </div>
                    </div>

                    <div className="mt-3 flex justify-end">
                      <button
                        type="button"
                        onClick={() => removeOrderItem(index)}
                        className="px-3 py-1 bg-red-600 text-white text-sm rounded-md hover:bg-red-700"
                      >
                        删除
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 订单总计 */}
          <div className="border-t pt-4">
            <div className="flex justify-between items-center text-lg font-semibold">
              <span>订单总计:</span>
              <span>¥{calculateTotal().toFixed(2)}</span>
            </div>
          </div>

          {/* 提交按钮 */}
          <div className="pt-6 border-t">
            <div className="flex space-x-3">
              <button
                type="submit"
                disabled={loading || !selectedCustomer || orderItems.length === 0}
                className="px-6 py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
              >
                {loading ? '创建中...' : '创建订单'}
              </button>
              <Link
                href="/orders"
                className="px-6 py-3 bg-gray-600 text-white rounded-md hover:bg-gray-700"
              >
                取消
              </Link>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}